<template>
  <div class="obj-to-3dtiles">
    <div class="handle-box">
      <el-form label-width="120px" :inline="false" size="normal">
        <el-row :gutter="20">
          <el-col :span="12">
            <p class="title">单体化三维模型轻量化</p>
            <el-form-item label="输入路径">
              <el-input v-model="inputPath" size="mini" style="width: calc(100% - 50px)" disabled></el-input>
              <el-button size="mini" @click="openFiles('inputPath')">···</el-button>
            </el-form-item>
            <el-form-item label="输出路径">
              <el-input v-model="outputPath" size="mini" style="width: calc(100% - 50px)" disabled></el-input>
              <el-button size="mini" @click="openFiles('outputPath')">···</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <p class="title">轻量化参数选项</p>
            <el-form-item label="Y轴作为Z">
              <el-switch v-model="upAxisYToZ">
              </el-switch>
            </el-form-item>
            <el-form-item label="设置层级">
              <el-input v-model.number="startLevel" size="mini" style="width: 45%"></el-input>
              <span style="color: #fff;margin: 0 5px">-</span>
              <el-input v-model.number="endLevel" size="mini" style="width: 45%"></el-input>
            </el-form-item>
            <el-form-item label="纹理合并">
              <el-switch v-model="mergeTexture">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="footer">
        <el-button size="mini" @click="openLogDialog(questId)" v-if="questId">日志</el-button>
        <el-button type="primary" size="mini" @click="startProcessing">开始处理</el-button>
      </div>
    </div>
    <el-dialog title="选择文件夹" :visible.sync="fileSelectShow" width="30%" @close="deselect" :destroy-on-close="true"
      :close-on-click-modal="false">
      <div class="file-box" v-loading="fileLoading">
        <el-scrollbar style="height:calc(100% - 30px);">
          <el-tree :props="props" :load="loadFileNode" lazy :expand-on-click-node="false" @node-click="selectFile">
          </el-tree>
        </el-scrollbar>
        <el-input v-model="folderAddress" size="mini" disabled></el-input>
      </div>
      <span slot="footer">
        <el-button @click="deselect">取消</el-button>
        <el-button type="primary" @click="definiteSelect">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="日志" :visible.sync="logShow" width="60%" @close="cancel" :close-on-click-modal="false">
      <div class="log-dialog">
        <div class="scroll-box">
          <div class="log-item" v-for="(item, index) in logData" :key="index">{{ item.log }}</div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="cancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { xml2js } from 'xml-js';
import coordSystem from './../../assets/coordSystem.json'
export default {
  data () {
    return {
      questId: null,
      logData: [],
      logShow: false,
      upAxisYToZ: false,
      mergeTexture: true,
      inputPath: '',
      outputPath: '',
      metadata: '',
      metadataSrs: '',
      SRSOrigin: '',
      selectProj: '',
      projList: [],
      startLevel: 8,
      endLevel: 20,
      fileSelectShow: false,
      fileLoading: false,
      folderAddress: '',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      needSetField: '',
      timer: null
    };
  },
  methods: {
    // 关闭日志
    cancel () {
      this.logShow = false
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    fileListChange (event) {
      const file = event.target.files[0];
      const reader = new FileReader();
      let that = this
      reader.onload = (e) => {
        const xmlContent = e.target.result; // 读取文件内容
        const options = { ignoreComment: true, alwaysChildren: true }; // 配置选项
        const json = xml2js(xmlContent, options); // 将XML转换为JSON
        that.metadataSrs = json.elements[0].elements[0].elements[0].text
        that.metadata = that.metadataSrs.split(':')[1]
        that.SRSOrigin = json.elements[0].elements[1].elements[0].text
        that.selectChange()
      };
      reader.readAsText(file)
    },
    async startProcessing () {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      if (!this.startLevel || !this.endLevel) {
        this.$message.warning('请配置层级')
      }
      let level = ''
      if (this.startLevel && this.endLevel) {
        level = `${this.startLevel}-${this.endLevel}`
      } else {
        if (this.startLevel) {
          level = this.startLevel
        }
        if (this.endLevel) {
          level = this.endLevel
        }
      }
      const id = new Date().getTime()
      let convertParams = {
        "id": id,
        "objRootDir": this.inputPath,
        "tileRootDir": this.outputPath,
        "upAxisYToZ": this.upAxisYToZ,
        "mergeTexture": this.mergeTexture,
        "level": level,
        "mode": "mode_fast"
      }
      // 用于存储任务的参数
      let params = {
        id: id,
        name: "OBJ转3Dtiles",
        info: JSON.stringify(convertParams),
        path: convertParams.tileRootDir,
        // 2:OBJ to 3Dtiles
        type: 4
      }
      await axios.post(`${window.nodeApiIp}/saveService/insertDemService`, params)
      let resp = await axios.post(`${window.nodeApiIp}/routineCall/updateObjTo3DtilesConfig`, convertParams)
      if (resp.data.status == 200) {
        this.$message.success(resp.data.msg)
        setTimeout(() => {
          this.questId = id
          this.openLogDialog(id)
        }, 2000)
      }
    },
    openFiles (field) {
      this.needSetField = field
      this.fileSelectShow = true
      this.folderAddress = ''
    },
    // dialog确定选择
    definiteSelect () {
      this.fileSelectShow = false
      this[this.needSetField] = this.folderAddress
    },
    // 获取文件夹地址
    selectFile (data, node) {
      let path = this.getPathFromTree(node)
      this.folderAddress = path
    },
    // 获取文件夹
    async getDirectory (path) {
      let res = await axios.post(`${window.nodeApiIp}/directory/getDirectory`, {
        path: path
      })
      if (res.data.directory.length > 0) {
        let fileList = []
        res.data.directory.forEach(item => {
          let ob = {
            name: item.name,
            children: [],
            leaf: false
          }
          fileList.push(ob)
        })
        return fileList
      } else {
        return false
      }
    },
    // 获取盘符
    async getDisk () {
      this.fileLoading = true
      let res = await axios.get(`${window.nodeApiIp}/directory/driveLetters`)
      this.fileLoading = false
      let fileList = []
      res.data.forEach(item => {
        let ob = {
          name: item,
          children: [],
          leaf: false
        }
        fileList.push(ob)
      })
      return fileList
    },
    // 文件夹树
    async loadFileNode (node, resolve) {
      if (node.level === 0) {
        let records = await this.getDisk()
        return resolve(records)
      } else {
        let path = this.getPathFromTree(node)
        let records = await this.getDirectory(path)
        if (records) {
          return resolve(records)
        } else {
          node.data.leaf = true
          return resolve([])
        }
      }
    },
    // 从树中获取到文件路径
    getPathFromTree (node) {
      let path = ''
      if (node.parent.data) {
        let parentPath = this.getPathFromTree(node.parent)
        path = parentPath + node.data.name + "\\"
      } else {
        path = node.data.name + ":\\"
      }
      return path
    },
    deselect () {
      this.fileSelectShow = false
    },
    selectChange () {
      this.projList.forEach(item => {
        if (item.id == this.metadata) {
          this.selectProj = item.strProject
        }
      })
    },
    getCoordSystem () {
      this.projList = coordSystem
    },
    // 获取日志并定位到最下方
    async getLogToBottom (id) {
      let res = await axios.get(`${window.nodeApiIp}/saveService/getLogById?id=${id}`)
      if (res.data.section == 1) {
        clearInterval(this.timer)
        this.timer = null
        this.$message.success('转换完成')
      }
      this.logData = res.data.logs
      this.$nextTick(() => {
        var container = document.querySelector('.scroll-box');
        container.scrollTop = container.scrollHeight
      })
    },
    // 打开日志弹窗
    openLogDialog (id) {
      this.logShow = true
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.timer = setInterval(() => {
        this.getLogToBottom(id)
      }, 2000)
      this.getLogToBottom(id)
    }
  },
  created () {
    this.getCoordSystem()
  },
  mounted () { },
  beforeDestroy () {
    clearInterval(this.timer)
    this.timer = null
  }
};
</script>
<style lang="less">
.obj-to-3dtiles {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .handle-box {
    width: 1200px;
    height: 400px;
    background: #1A1A1A;
    padding: 10px 30px;
    box-sizing: border-box;
    background: rgba(4, 11, 20, 0.63);
    border: 1px solid rgba(22, 93, 202, 0.6);
    border-radius: 10px;

    .title {
      color: #fff;
    }

    .el-form-item__label {
      color: #fff
    }

    .footer {
      width: 100%;
      height: 50px;
      display: flex;
      justify-content: end;
      align-items: center;
    }
  }

  .file-box {
    width: 100%;
    height: 400px
  }

  .log-dialog {
    width: 100%;
    height: 510px;

    .scroll-box {
      width: 100%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;

      .log-item {
        margin: 10px 10px;
        line-height: 30px;
      }
    }
  }
}
</style>